package com.platform.web.controller.system;

import java.util.Date;
import java.util.List;

import com.platform.common.core.domain.entity.SysUser;
import com.platform.system.domain.ProPublicProducproOrder;
import com.platform.system.mapper.SysUserMapper;
import com.platform.system.service.IProPublicProducproOrderService;
import com.platform.system.service.ISysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.platform.common.annotation.Log;
import com.platform.common.core.controller.BaseController;
import com.platform.common.core.domain.AjaxResult;
import com.platform.common.enums.BusinessType;
import com.platform.system.domain.ProPublicProduct;
import com.platform.system.service.IProPublicProductService;
import com.platform.common.utils.poi.ExcelUtil;
import com.platform.common.core.page.TableDataInfo;

/**
 * 公益信息Controller
 *
 * @author platform
 * @date 2025-02-23
 */
@Tag(name = "公益信息", description = "")
@RestController
@RequestMapping("/system/public_product")
public class ProPublicProductController extends BaseController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private IProPublicProductService proPublicProductService;

    @Autowired
    private IProPublicProducproOrderService proPublicProducproOrderService;

    /**
     * 查询公益信息列表
     */
    @Operation(summary = "查询公益信息列表")
    @GetMapping("/listAll")
    public AjaxResult listAll(ProPublicProduct proPublicProduct) {
        List<ProPublicProduct> list = proPublicProductService.selectProPublicProductListAll(proPublicProduct);
        return success(list);
    }

    /**
     * 查询公益信息列表
     */
    @Operation(summary = "查询公益信息列表")
    @PreAuthorize("@ss.hasPermi('system:public_product:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProPublicProduct proPublicProduct) {
        startPage();
        List<ProPublicProduct> list = proPublicProductService.selectProPublicProductList(proPublicProduct);
        return getDataTable(list);
    }

    /**
     * 导出公益信息列表
     */
    @Operation(summary = "导出公益信息列表")
    @PreAuthorize("@ss.hasPermi('system:public_product:export')")
    @Log(title = "公益信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProPublicProduct proPublicProduct) {
        List<ProPublicProduct> list = proPublicProductService.selectProPublicProductList(proPublicProduct);
        ExcelUtil<ProPublicProduct> util = new ExcelUtil<ProPublicProduct>(ProPublicProduct.class);
        util.exportExcel(response, list, "公益信息数据");
    }

    /**
     * 获取公益信息详细信息
     */
    @Operation(summary = "获取公益信息详细信息")
//    @PreAuthorize("@ss.hasPermi('system:public_product:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(proPublicProductService.selectProPublicProductById(id));
    }

    /**
     * 新增公益信息
     */
    @Operation(summary = "新增公益信息")
    @PreAuthorize("@ss.hasPermi('system:public_product:add')")
    @Log(title = "公益信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProPublicProduct proPublicProduct) {
        proPublicProduct.setUserId(getUserId());
        proPublicProduct.setCreateBy(getUsername());
        return toAjax(proPublicProductService.insertProPublicProduct(proPublicProduct));
    }

    /**
     * 修改公益信息
     */
    @Operation(summary = "修改公益信息")
    @PreAuthorize("@ss.hasPermi('system:public_product:edit')")
    @Log(title = "公益信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProPublicProduct proPublicProduct) {
        proPublicProduct.setUpdateBy(getUsername());
        return toAjax(proPublicProductService.updateProPublicProduct(proPublicProduct));
    }

    /**
     * 删除公益信息
     */
    @Operation(summary = "删除公益信息")
    @PreAuthorize("@ss.hasPermi('system:public_product:remove')")
    @Log(title = "公益信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(proPublicProductService.deleteProPublicProductByIds(ids));
    }

    @Transactional
    @Operation(summary = "兑换")
    @GetMapping("/pay/{id}")
    public AjaxResult pay(@PathVariable Long id,
                          @RequestParam("count") Long count) {
        ProPublicProduct proPublicProduct = proPublicProductService.selectProPublicProductById(id);
        // 销量+1
        Long sales = proPublicProduct.getSales();
        proPublicProduct.setSales(sales + count);
        // 库存-1
        Long store = proPublicProduct.getStore();
        proPublicProduct.setStore(store - count);
        proPublicProductService.updateProPublicProduct(proPublicProduct);

        ProPublicProducproOrder proPublicProducproOrder = new ProPublicProducproOrder();
        proPublicProducproOrder.setPublicProducproId(proPublicProduct.getId());
        proPublicProducproOrder.setPublicProducproName(proPublicProduct.getName());
        proPublicProducproOrder.setPublicProducproImg(proPublicProduct.getImgs());
        proPublicProducproOrder.setCount(count);
        Long totalPoints = proPublicProduct.getPoints() * count;
        proPublicProducproOrder.setTotalPoints(totalPoints);
        proPublicProducproOrder.setAddress(proPublicProduct.getAddress());
        proPublicProducproOrder.setUserId(getUserId());
        proPublicProducproOrder.setCreateBy(getUsername());
        proPublicProducproOrder.setCreateTime(new Date());
        proPublicProducproOrderService.insertProPublicProducproOrder(proPublicProducproOrder);

        Long userId = getUserId();
        SysUser user = sysUserService.selectUserById(userId);

        if (user.getPoints() - totalPoints <= 0) {
            return error("积分不足");
        }

        // 更新积分
        sysUserMapper.updateUserPoints(userId, user.getPoints() - totalPoints);
        return success();
    }
}
